<template>
  <!-- // 分配角色 -->
  <div>
    <el-checkbox-group v-model="roleIds">
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>

    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="hSubmit">确定</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </div>
  </div>
</template>

<script>
import { getAllRole } from '@/api/role'
import { getUserDetailInfo } from '@/api/user'
import { assignRoles } from '@/api/employees'

export default {
  name: 'AssignRole',
  props: {
    id: {
      type: Number,
      required: true
    }
  },

  data() {
    return {
      roleIds: [], // 选择了的角色放入这个数组
      roleList: [] // 获取到了所有角色放入这个数组
    }
  },

  async created() {
    this.loadGetRole()
    this.loadUserRole()
  },

  methods: {
    closeDialog() {
      this.$emit('cancel')
    },
    // 获取所以的角色列表
    async loadGetRole() {
      try {
        const { data } = await getAllRole({ page: 1, pagesize: 999 })
        console.log(data)
        console.log(data.rows)
        this.roleList = data.rows
      } catch (error) {
        console.log(error)
      }
    },
    // 发请求获取当前点击的用户所拥有的角色
    async loadUserRole() {
      try {
        const { data } = await getUserDetailInfo(this.id)
        this.roleIds = data.roleIds
      } catch (error) {
        console.log(error)
      }
    },
    // 点击确定的时候给员工添加角色
    async hSubmit() {
      try {
        // 发请求
        const res = await assignRoles({ id: this.id, roleIds: this.roleIds })
        // 提醒用户
        this.$message.success(res.message)
        // 关闭dialog
        this.$emit('cancel')
      } catch (error) {
        this.message.error(error.message)
      }
    }
  }
}
</script>
